<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Mailer
 *
 * @category  Common
 */
class MailerAction extends Action
{


	private $_config = array(); //系统配置
	private $_search = array(); //全局标签


	function _initialize()
	{
	    vendor('PHPMailer.class#phpmailer');
		$this->init();
	}


	//初始化全局标签
	public function init()
	{
		$_config = F('cache_site_configs');
		$_config['site_domain'] = get_site_domain();
		$_config['site_link'] = "<a href='{$_config['site_url']}'>{$_config['site_name']}</a>";
		$this->_search = array(
			array('s' => '{$software_link}',      'r' => $_config['software_link']),
			array('s' => '{$software_name}',      'r' => $_config['software_name']),
			array('s' => '{$software_version}',   'r' => $_config['software_version']),
			array('s' => '{$software_copyright}', 'r' => $_config['software_copyright']),
			array('s' => '{$current_time}',       'r' => format_date()),
			array('s' => '{$site_name}',          'r' => $_config['site_name']),
			array('s' => '{$site_url}',           'r' => $_config['site_url']),
			array('s' => '{$site_link}',          'r' => $_config['site_link']),
			array('s' => '{$site_logo}',          'r' => $_config['site_logo']),
			array('s' => '{$site_description}',   'r' => $_config['site_description']),
			array('s' => '{$contact_email}',      'r' => $_config['contact_email']),
			array('s' => '{$email_signature}',    'r' => $_config['email_signature']),
		);
		$this->_config = $_config;
	}


	//重置密码
	public function resetPassword($userID)
	{
		$identifier = 'password_reset';

		$User = M('User');
		$user = $User->find($userID);

		$expiredTime = 86400 + time();
		cookie('password_reset_link', 1, $expiredTime);
		$password = kg_rand_string();
		$auth = kg_auth_code($userID ."\t". $password. "\t" .$expiredTime, 'encode');
		$href = $this->_config['site_domain'] . U('Account/resetPassword', array('auth' => $auth));
        $passwordResetLink = "<a href='{$href}'>". $href ."</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $user['username']),
			array('s' => '{$password_reset_link}','r' => $passwordResetLink),
			array('s' => '{$expired_time}', 'r' => format_date($expiredTime)),
			array('s' => '{$password}', 'r' => $password),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $user['username'] .'<'. $user['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}

	//注册欢迎信息
	public function welcomeMessage($userID)
	{
		$identifier = 'welcome_message';

		$User = M('User');
		$user = $User->find($userID);

		$askHref = $this->_config['site_domain']. U('Question/ask');
		$answerHref = $this->_config['site_domain']. U('Category/index', array('status' => 1));
		$discoverHref = $this->_config['site_domain']. U('Category/index', array('status' => 3));

		$askLink = "<a href='{$askHref}'>".L('ask')."</a>";
		$answerLink = "<a href='{$answerHref}'>".L('answer')."</a>";
		$discoverLink = "<a href='{$discoverHref}'>".L('discover')."</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $user['username']),
			array('s' => '{$ask_link}', 'r' => $askLink),
			array('s' => '{$answer_link}', 'r' => $answerLink),
			array('s' => '{$discover_link}', 'r' => $discoverLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $user['username'] .'<'. $user['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 确认注册账号
	 *
	 * @param int $userID 用户ID
	 * @return bool
	 */
	public function confirmAccount($userID)
	{
		$identifier = 'account_confirmation';

		$User = M('User');
		$user = $User->find($userID);

		$auth = kg_auth_code($user['user_id'], 'encode');
		$href = $this->_config['site_domain']. U('Account/confirmAccount', array('auth' => $auth));
		$confirmLink = "<a href='{$href}'>{$href}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $user['username']),
			array('s' => '{$confirm_link}', 'r' => $confirmLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $user['username'] .'<'. $user['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * 邮件地址验证
	 *
	 * @param int $userID 用户ID
	 * @param string $email 待验证邮件地址
	 * @return bool
	 */
	public function validateEmail($userID, $email)
	{
		$identifier = 'email_validation';

		$User = M('User');
		$user = $User->find($userID);

		$auth = kg_auth_code($userID ."\t". $email, 'encode');
		$href = $this->_config['site_domain']. U('Account/validateEmail', array('auth' => $auth));
		$validationLink = "<a href='{$href}'>{$href}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $user['username']),
			array('s' => '{$validation_link}', 'r' => $validationLink),
		);
		
		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $user['username'] .'<'. $email .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 新粉丝通知
	 *
	 * @param  int $sourceID
	 * @param  int $targetID
	 * @return bool
	 */
	public function newFollowerAlert($sourceID, $targetID)
	{
		$identifier = 'new_follower_alert';

		$User 	= M('User');

		$sourceUser = $User->find($sourceID);
		$targetUser = $User->find($targetID);

		$href = format_user_url($sourceUser['user_id'], $sourceUser['username']);
		$followerProfileLink = "<a href='{$href}'>{$href}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $targetUser['username']),
			array('s' => '{$follower}', 'r' => $sourceUser['username']),
			array('s' => '{$follower_profile_link}', 'r' => $followerProfileLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $targetUser['username'] .'<'. $targetUser['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 问题有新答案通知
	 *
	 * @param  int $ansID 答案ID
	 * @return bool
	 */
	public function newAnswerAlert($ansID)
	{
		$identifier = 'new_answer_alert';

		$Answer    = M('Answer');
		$Question  = M('Question');
		$User 	   = M('User');

		$answer    = $Answer->find($ansID);
		$question  = $Question->find($answer['question_id']);
		$asker     = $User->find($question['poster_id']);

		$href = format_question_url($question['question_id'], $question['title']);
		$questionLink = "<a href='{$href}'>{$question['title']}</a>";

		$href = format_user_url($answer['poster_id'], $answer['poster_name']);
		$answererProfileLink = "<a href='{$href}'>{$answer['poster_name']}</a>";
		
		$auth = kg_auth_code($question['poster_id'] ."\t". $question['question_id'], 'encode');
		$href = $this->_config['site_domain']. U('Notification/stopAnswerAlert', array('auth' => $auth));
		$unsubscribeLink = "<a href='{$href}'>{$href}</a>";
		
		$search = array(
			array('s' => '{$username}', 'r' => $asker['username']),
			array('s' => '{$question_link}', 'r' => $questionLink),
			array('s' => '{$latest_answer_details}', 'r' => parse_markup($answer['details'])),
			array('s' => '{$answerer_profile_link}', 'r' => $answererProfileLink),
			array('s' => '{$answer_create_time}', 'r' => format_date($answer['create_time'])),
			array('s' => '{$unsubscribe_link}', 'r' => $unsubscribeLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $asker['username'] .'<'. $asker['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 回答有新评论通知
	 *
	 * @param  int 评论ID
	 * @return bool
	 */
	public function newAnswerCommentAlert($cmtID)
	{
		$identifier = 'new_answer_comment_alert';

		$User     = M('User');
		$Comment  = M('Comment');
		$Answer   = M('Answer');
		$Question = M('Question');

		$comment  = $Comment->find($cmtID);
		$answer   = $Answer->find($comment['related_id']);
		$question = $Question->find($answer['question_id']);
		$answerer = $User->find($answer['poster_id']);

		$href = format_question_url($question['question_id'], $question['title']);
		$questionLink = "<a href='{$href}'>{$question['title']}</a>";

		$href = format_user_url($comment['poster_id'], $comment['poster_name']);
		$commentatorProfileLink = "<a href='{$href}'>{$comment['poster_name']}</a>";
		
		$auth = kg_auth_code($userID ."\t". $question['question_id'], 'encode');
		$href = $this->_config['site_domain']. U('Notification/stopCommentAlert', array('auth' => $auth));
		$unsubscribeLink = "<a href='{$href}'>{$href}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $answerer['username']),
			array('s' => '{$question_link}', 'r' => $questionLink),
			array('s' => '{$comment_details}', 'r' => parse_markup($comment['details'])),
			array('s' => '{$commentator_profile_link}', 'r' => $commentatorProfileLink),
			array('s' => '{$comment_create_time}', 'r' => format_date($comment['create_time'])),
			array('s' => '{$unsubscribe_link}', 'r' => $unsubscribeLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $answerer['username'] .'<'. $answerer['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 票选最佳答案通知
	 *
	 * @param  int $qstID 问题ID
	 * @return bool
	 */
	public function votedAsBestAnswerAlert($qstID)
	{
		$identifier = 'voted_as_best_answer_alert';

		$Question  = M('Question');
		$User 	   = M('User');

		$question  = $Question->find($qstID);
		$asker     = $User->find($question['poster_id']);

		$href = format_question_url($question['question_id'], $question['title']);
		$questionLink = "<a href='{$href}'>{$question['title']}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $asker['username']),
			array('s' => '{$question_link}', 'r' => $questionLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $asker['username'] .'<'. $asker['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 最佳答案通知(通知回答者)
	 *
	 * @param  int $ansID 答案ID
	 * @return bool
	 */
	public function selectedAsBestAnswerAlert($ansID)
	{
		$identifier = 'selected_as_best_answer_alert';

		$Answer   = M('Answer');
		$Question = M('Question');
		$User 	  = M('User');

		$answer    = $Answer->find($ansID);
		$question  = $Question->find($answer['question_id']);
		$answerer  = $User->find($answer['poster_id']);

		$href = format_question_url($question['question_id'], $question['title']);
		$questionLink = "<a href='{$href}'>{$question['title']}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $answerer['username']),
			array('s' => '{$question_link}', 'r' => $questionLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $answerer['username'] .'<'. $answerer['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 关闭过期问题通知(通知提问者)
	 *
	 * @param  int $qstID 问题ID
	 * @return bool
	 */
	public function closeExpiredQuestionAlert($qstID)
	{
		$identifier = 'close_expired_question_alert';

		$Question = M('Question');
		$User 	  = M('User');

		$question  = $Question->find($qstID);
		$asker     = $User->find($question['poster_id']);

		$href = format_question_url($question['question_id'], $question['title']);
		$questionLink = "<a href='{$href}'>{$question['title']}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $asker['username']),
			array('s' => '{$question_link}', 'r' => $questionLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $asker['username'] .'<'. $asker['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * @desc 关闭未解决问题通知(通知提问者)
	 *
	 * @param  int $qstID 问题ID
	 * @return bool
	 */
	public function closeUnresolvedQuestionAlert($qstID)
	{
		$identifier = 'close_unresolved_question_alert';

		$Question = M('Question');
		$User 	  = M('User');

		$question  = $Question->find($qstID);
		$asker     = $User->find($question['poster_id']);

		$href = format_question_url($question['question_id'], $question['title']);
		$questionLink = "<a href='{$href}'>{$question['title']}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $asker['username']),
			array('s' => '{$question_link}', 'r' => $questionLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $asker['username'] .'<'. $asker['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}

	
	
	/**
	 * @desc 新入团申请(通知leader)
	 *
	 * @param  int $userID 队员ID
	 * @param  int teamID 团队ID
	 * @return bool
	 */
	public function newTeammateAlert($userID, $teamID)
	{
		$identifier = 'new_teammate_alert';
		
		$Team = M('Team');  
		$User = M('User');

		$team = $Team->find($teamID);
		$user = $User->find($userID);
		$leader = $User->find($team['leader_id']);

		$href = format_user_url($user['user_id'], $user['username']);
		$userLink = "<a href='{$href}'>{$user['username']}</a>";
		
		$href = format_team_url($team['team_id'], $team['name']);
		$teamLink = "<a href='{$href}'>{$team['name']}</a>";
		
		$href = $this->_config['site_domain']. U('Team/approveUser', array('uid'=>$userID,'tid'=>$teamID,'type'=>'approve'));
		$approveLink = "<a href='{$href}'>{$href}</a>";
		
		$href = $this->_config['site_domain']. U('Team/approveUser', array('uid'=>$userID,'tid'=>$teamID,'type'=>'disapprove'));
		$disapproveLink = "<a href='{$href}'>{$href}</a>";

		$search = array(
			array('s' => '{$team_leader}', 'r' => $leader['username']),
			array('s' => '{$team_link}', 'r' => $teamLink),
			array('s' => '{$user_link}', 'r' => $userLink),
			array('s' => '{$approve_link}', 'r' => $approveLink),
			array('s' => '{$disapprove_link}', 'r' => $disapproveLink),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $leader['username'] .'<'. $leader['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}
	

	/**
	 * @desc 分享问题给朋友
	 *
	 * @param int $userID 发件人ID
	 * @param int $qstID 问题ID
	 * @param string $recipient 收件人地址
	 * @param string $message 邮件内容
	 * @return bool
	 */
	public function shareQuestion($userID, $qstID, $recipient, $message)
	{
		$identifier = 'share_question_to_friends';

		$Question = M('Question');
		$User     = M('User');

		$question  = $Question->find($qstID);
		$sender    = $User->find($userID);

		$href = format_question_url($question['question_id'], $question['title']);
		$questionLink = "<a href='{$href}'>{$question['title']}</a>";

		$href = format_user_url($sender['user_id'], $sender['username']);
		$senderProfileLink = "<a href='{$href}'>{$sender['username']}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $sender['username']),
			array('s' => '{$question_link}', 'r' => $questionLink),
			array('s' => '{$sender_profile_link}', 'r' => $senderProfileLink),
			array('s' => '{$message}', 'r' => $message),
		);
		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $recipient;
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);
		$from = $sender['username'] .'<'. $sender['email'] .'>';

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * 会员间联系信息
	 *
	 * @param int $fromUserID 发件会员ID
	 * @param int $toUserID 收件会员ID
	 * @param string $subject 消息主题
	 * @param string $message 消息内容
	 * @return bool
	 */
	public function pm($fromUserID, $toUserID, $subject, $message)
	{
		$identifier = 'private_message';

		$User = M('User');
		$sender = $User->find($fromUserID);
		$recipient = $User->find($toUserID);

		$href = format_user_url($sender['user_id'], $sender['username']);
		$senderProfileLink = "<a href='{$href}'>{$sender['username']}</a>";

		$search = array(
			array('s' => '{$username}', 'r' => $recipient['username']),
			array('s' => '{$sender_profile_link}', 'r' => $senderProfileLink),
			array('s' => '{$subject}', 'r' => $subject),
			array('s' => '{$message}', 'r' => $message),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $recipient['username'] .'<'. $recipient['email'] .'>';
		$message = $this->replaceTags($tags, $tpl['message']);
		$from = $sender['username'] .'<'. $sender['email'] .'>';

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * 邀请注册
	 *
	 * @param int $userID 邀请人ID
	 * @param string $recipient 收件人
	 * @return bool
	 */
	public function friendInvitation($userID, $recipient, $message)
	{
	    $identifier = 'friend_invitation';

		$User = M('User');
		$inviter = $User->find($userID);

		$href = format_user_url($inviter['user_id'], $inviter['username']);
		$inviterLink = "<a href='{$href}'>{$inviter['username']}</a>";
		$hash = kg_auth_code($inviter['user_id'], 'encode');
		$href = $this->_config['site_domain']. U('Account/login', array('inviter'=>$hash));
		$registrationLink = "<a href='{$href}'>{$href}</a>";

		$search = array(
			array('s' => '{$inviter}', 'r' => $inviter['username']),
			array('s' => '{$inviter_link}', 'r' => $inviterLink),
			array('s' => '{$registration_link}', 'r' => $registrationLink),
			array('s' => '{$message}', 'r' => $message),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $recipient;
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);
		$from = $inviter['username'] .'<'. $inviter['email'] .'>';

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	/**
	 * 生日祝福
	 *
	 * @param int $userID
	 * @return bool
	 */
	public function birthdayWishes($userID)
	{
	    $identifier = 'birthday_wishes';

	    $User = M('User');
	    $user = $User->find($userID);

		$search = array(
			array('s' => '{$username}', 'r' => $user['username']),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$to = $user['username'] .'<'. $user['email'] .'>';
		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}

	/**
	 * 测试邮件
	 *
	 * @param string $to 收件人
	 * @param string $subject 邮件主题
	 * @param string $message 邮件内容
	 * @param string $from 发件人
	 * @return bool
	 */
	public function test($to, $subject, $message, $from)
	{
		$identifier = 'check_mailer_configuration';

		$search = array(
			array('s' => '{$subject}', 'r' => $subject),
			array('s' => '{$message}', 'r' => $message),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		return $result = $this->send($to, $subject, $message, $from);
	}


	/**
	 * 发送newsletter
	 *
	 * @param string $to 收件人
	 * @param string $subject 主题
	 * @param string $message 内容
	 * @param int $userID 用户ID
	 * @return bool
	 */
	public function newsletter($to, $subject, $message, $userID=0)
	{
		$identifier = 'newsletter';

		$unsubscribeLink = $this->_config['site_domain']. U('User/privacy', array('uid' => $userID, 'type' => 'privacy'));
		$search = array(
			array('s' => '{$unsubscribe_link}', 'r' => $unsubscribeLink),
			array('s' => '{$subject}', 'r' => $subject),
			array('s' => '{$message}', 'r' => $message),
		);

		$tags = array_merge($this->_search, $search);
		$tpl = $this->getEmailTemplate($identifier);

		$subject = $this->replaceTags($tags, $tpl['subject']);
		$message = $this->replaceTags($tags, $tpl['message']);

		$result = $this->send($to, $subject, $message);
		$this->updateEmailStatistics($identifier, $result);
		return $result;
	}


	//标签替换
	public function replaceTags($list, $string)
	{
		foreach ($list as $value)
		{
			$content = str_replace($value['s'], $value['r'], $string);
			$string = $content;
		}
		return $content;
	}


	/**
	 * 取得邮件模板,邮件模板由内容模板(后台可编辑)和全局的外框布局(类似信纸)组成
	 *
	 * @param string $identifier 标识码
	 * @return string
	 */
	private function getEmailTemplate($identifier='')
	{
		$lang = $this->_config['default_lang'];
		if (!$file = F('cache_email_templates'))
		{
			$file = cache_email_templates();
		}
		$tpl = isset($file[$lang][$identifier]) ? $file[$lang][$identifier] : $file['en-us'][$identifier];
		if (empty($tpl))
		{
			$tpl = array('subject' => '', 'message' => '');
		}
		$tpl['subject'] = strip_tags($tpl['subject']);
		// [url][/url]标签中url被urlencode,可能破坏标签的替换
		$tpl['message'] = parse_markup($tpl['message'], C('MARKUP_MODE'));
		//获取邮件模板布局
		$path = TMPL_PATH .$this->_config['default_theme'].'/email_template_layout.html';
		if (!file_exists($path))
		{
		 	$path = TMPL_PATH .'Default/email_template_layout.html';
		}
		$layout = $this->replaceTags($this->_search, file_get_contents($path));
		$tpl['message'] = str_replace('{$message}', $tpl['message'], $layout);

		return $tpl;
	}


	/**
	 * 更新邮件的统计计数
	 * @access private
	 * @param string $identifier 邮件标识码
	 * @param bool $success 发送是否成功
	 * @return mixed
	 */
	private function updateEmailStatistics($identifier, $success)
	{
		$Tpl = M('EmailTemplate');

		$map = array('identifier' => $identifier);
		$data = array(
			'total_count' => array('exp','total_count+1'),
			'last_send_time' => time(),
		);
		if (!$success)
		{
			$data['failed_count'] = array('exp', 'failed_count+1');
		}
        $Tpl->where($map)->save($data);
	}


	/**
	 * PHPMailer发送邮件
	 *
	 * @param string $to 收件人
	 * @param string $subject 邮件主题
	 * @param string $message 邮件内容
	 * @param string $from 发件人
	 * @return bool
	 */
	protected function send($to, $subject, $message, $from='')
	{
		$Mailer = new PHPMailer();

	    $mailerType   = $this->_config['mailer_type'];
	    $smtpEncrypt  = $this->_config['smtp_encrypt'];
	    $smtpAuth	  = $this->_config['smtp_auth'] ? true : false;
	    $smtpHost     = $this->_config['smtp_host'];
	    $smtpPort     = $this->_config['smtp_port'];
	    $smtpUser     = $this->_config['smtp_auth_username'];
	    $smtpPassword = $this->_config['smtp_auth_password'];
	    $mailFrom     = $from ? $from : $this->_config['return_email'];

	  	list($name, $from) = $this->parseEmail($mailFrom);

	    if ('mail' == $mailerType)
	    {
	    	$Mailer->IsMail();
	    }
	    elseif ('smtp' == $mailerType)
	    {
	    	$Mailer->IsSMTP();
	    	$Mailer->SMTPAuth   = $smtpAuth;
            $Mailer->SMTPSecure = $smtpEncrypt;
            $Mailer->Host       = $smtpHost;
            $Mailer->Port       = $smtpPort ? $mailPort : 25;
            $Mailer->Username   = $smtpUser;
            $Mailer->Password   = $smtpPassword;
	    }

		$Mailer->SMTPDebug  = false;
        $Mailer->CharSet    = 'UTF-8';
        $Mailer->From       = $from;
        $Mailer->FromName   = $name;
        $Mailer->AddReplyTo($from, $name);

        $Mailer->Subject    = $subject;
        $Mailer->AltBody    = "To view the message, please use an HTML compatible email viewer!";
        $Mailer->WordWrap   = 50;
        $Mailer->MsgHTML($message);

        $addressList = explode(',', $to);
        foreach ($addressList as $address)
        {
        	list($name, $to) = $this->parseEmail($address);
        	$Mailer->AddAddress($to, $name);
        }
        $Mailer->IsHTML(true);
        $result = $Mailer->Send();
        if (C('MAILER_DEBUG') && !$result)
        {
        	echo $Mailer->ErrorInfo;
        }
        return $result;
	}


	/**
	 * @desc 分解email形如:"qqas<abc@gmail.com>"中的用户名和邮件地址
	 * @param string $str
	 * @return array
	 */
	private function parseEmail($str)
	{
		if (preg_match("/<(.*?)>/", $str, $matchs))
		{
	    	$email = trim($matchs[1]);
	    	$name  = trim(substr($str, 0, strpos($str, '<')));
	    }
	    else
	    {
	    	$email = trim($str);
	    	$name  = trim(substr($str, 0, strpos($str, '@')));
	    }
	    return array($name, $email);
	}

}
//end of class

/* End of file MailerAction.class.php */
/* Location: ./App/Lib/Action/MailerAction.class.php */
